from flask import Blueprint, render_template, flash, redirect, url_for, request
from app.forms import LoginForm
from app.models import User
from flask_login import login_user


bp = Blueprint('auth', __name__)


@bp.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).first()
        if user is None or not user.validate_password(form.password.data):
            flash('账号或密码错误！', 'warning')
            return redirect(url_for('auth.login'))
        if login_user(user, remember=form.remember_me.data):
            flash('登陆成功!', 'success')
            next_page = request.args.get('next')
            if next_page:
                return redirect(next_page)
            return redirect(url_for('site.index'))
        else:
            flash('账号异常！', 'warning')
            return redirect(url_for('auth.login'))

    return render_template('manage/auth/login.html', form=form)
